<template>
  <div class="main">
    <a-form-model id="formLogin" ref="form" class="user-layout-login" :model="form" :rules="rules">
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="account" tab="账户密码登录">
          <a-alert
            v-if="isLoginError"
            type="error"
            showIcon
            style="margin-bottom: 24px;"
            :message="loginErrorInfo"
            closable
            :after-close="handleCloseLoginError"
          />
          <a-form-model-item prop="tenantId">
            <a-select v-model="form.tenantId" size="large" placeholder="租户">
              <a-select-option v-for="(d, index) in tenant" :key="index" :value="d.tenantId">
                {{ d.tenantName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item prop="username">
            <a-input v-model="form.username" size="large" placeholder="用户名">
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="password">
            <a-input-password v-model="form.password" size="large" placeholder="密码">
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input-password>
          </a-form-model-item>
          <a-row :gutter="16" v-if="captchaOnOff">
            <a-col class="gutter-row" :span="16">
              <a-form-model-item prop="code">
                <a-input v-model="form.code" size="large" type="text" autocomplete="off" placeholder="验证码">
                  <a-icon slot="prefix" type="security-scan" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <img class="getCaptcha" :src="codeUrl" @click="getCode">
            </a-col>
          </a-row>
          <a-form-model-item prop="rememberMe">
            <!--        <a-checkbox :checked="form.rememberMe" @change="rememberMe">记住密码</a-checkbox>-->
          </a-form-model-item>
        </a-tab-pane>
        <a-tab-pane key="mobile" tab="手机号登录">
          <a-form-model-item prop="tenantId">
            <a-select v-model="form.tenantId" size="large" placeholder="租户">
              <a-select-option v-for="(d, index) in tenant" :key="index" :value="d.tenantId">
                {{ d.tenantName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item prop="phone">
            <a-input v-model="form.phone" size="large" type="text" autocomplete="off" placeholder="手机号">
              <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-model-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item prop="smsCode">
                <a-input size="large" type="text" placeholder="验证码" v-model="form.smsCode">
                  <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button
                class="getCaptcha"
                tabindex="-1"
                :disabled="state.smsSendBtn"
                @click="getCaptcha"
                v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
              ></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="logining"
          :disabled="logining"
          @click="handleSubmit"
        >确定
        </a-button>
      </a-form-item>
      <div class="user-login-other">
        <!--
          ruoyi后台不支持获取是否开启账户.
          故此处不做隐藏处理. 在ruoyi原前端中是在注册页面定义一个属性手动修改处理.
        -->
        <!--        <router-link class="register" :to="{ name: 'register' }">注册账户</router-link>-->
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getCodeImg, getTenant, getSmsCaptcha } from '@/api/login'
import { LOGIN_USERNAME, LOGIN_PASSWORD, LOGIN_REMEMBERME, TENANT_ID } from '@/store/mutation-types'
import storage from 'store'

export default {
  components: {},
  data () {
    return {
      // 激活tab
      customActiveKey: 'account',
      codeUrl: '',
      isLoginError: false,
      loginErrorInfo: '',
      form: {
        phone: undefined,
        type: 'account',
        smsCode: undefined,
        username: '',
        password: '',
        code: undefined,
        tenantId: undefined,
        uuid: '',
        rememberMe: false
      },
      tenant: [],
      rules: {
        tenantId: [{ required: true, message: '请选择租户', trigger: 'blur' }],
        username: [{ required: true, message: '请输入帐户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入正确的手机号', pattern: /^1[34578]\d{9}$/, trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      logining: false,
      captchaOnOff: true,
      state: {
        time: 60,
        loginBtn: false,
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    this.getStorage()
    this.getCode()
    this.getTenantData()
  },
  methods: {
    // 切换tab
    handleTabClick (key) {
      this.customActiveKey = key
      this.form.type = key
    },
    getCode () {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
        if (this.captchaOnOff) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.form.uuid = res.uuid
        }
      })
    },
    getStorage () {
      const username = storage.get(LOGIN_USERNAME)
      const password = storage.get(LOGIN_PASSWORD)
      const rememberMe = storage.get(LOGIN_REMEMBERME)
      if (username) {
        this.form = {
          username: username,
          password: password,
          rememberMe: rememberMe
        }
      }
    },
    getTenantData () {
      getTenant().then(res => {
        if (res.data) {
          this.tenant = res.data
        }
      })
    },
    rememberMe (e) {
      this.form.rememberMe = e.target.checked
    },
    ...mapActions(['Login', 'Logout']),
    handleSubmit () {
      this.logining = true
      let error = 0
      if (this.form.type === 'account') {
        this.$refs.form.validateField(['tenantId', 'username', 'password', 'code'], (val) => {
          if (val) {
            error = 1
          }
        })
      }
      if (this.form.type === 'mobile') {
        this.$refs.form.validateField(['tenantId', 'phone', 'smsCode'], (val) => {
          if (val) {
            error = 1
          }
        })
      }

      if (error === 1) {
        setTimeout(() => {
          this.logining = false
        }, 600)
        return
      }
      storage.set(TENANT_ID, this.form.tenantId)
      // if (this.form.rememberMe) {
      //   storage.set(TENANT_ID, this.form.tenantId)
      //   storage.set(LOGIN_USERNAME, this.form.username)
      //   storage.set(LOGIN_PASSWORD, this.form.password)
      //   storage.set(LOGIN_REMEMBERME, this.form.rememberMe)
      // } else {
      //   storage.remove(TENANT_ID)
      //   storage.remove(LOGIN_USERNAME)
      //   storage.remove(LOGIN_PASSWORD)
      //   storage.remove(LOGIN_REMEMBERME)
      // }
      this.Login(this.form)
        .then((res) => this.loginSuccess(res))
        .catch(err => this.requestFailed(err))
        .finally(() => {
          this.logining = false
        })
    },
    loginSuccess (res) {
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.handleCloseLoginError()
    },
    requestFailed (err) {
      this.isLoginError = true
      this.loginErrorInfo = err
      this.form.code = undefined
      if (this.captchaOnOff && this.form.type === 'account') {
        this.getCode()
      }
    },
    handleCloseLoginError () {
      this.isLoginError = false
      this.loginErrorInfo = ''
    },
    getCaptcha: function (e) {
      e.preventDefault()

      let error = 0
      this.$refs.form.validateField(['phone', 'tenantId'], (val) => {
        if (val) {
          error = 1
        }
      })
      // 验证通过
      if (error === 1) {
        return
      }
      storage.set(TENANT_ID, this.form.tenantId)
      this.state.smsSendBtn = true
      const interval = window.setInterval(() => {
        if (this.state.time-- <= 0) {
          this.state.time = 60
          this.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)

      const hide = this.$message.loading('验证码发送中..', 0)
      getSmsCaptcha(this.form.phone).then(res => {
        setTimeout(hide, 2500)
        this.$notification['success']({
          message: '提示',
          description: '验证码发送成功',
          duration: 8
        })
        setTimeout(hide, 1)
      }).catch(() => {
        setTimeout(hide, 1)
        clearInterval(interval)
        this.state.time = 60
        this.state.smsSendBtn = false
        this.isLoginError = true
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .register {
      float: right;
    }
  }
}
</style>
